import React, { useEffect, useRef, useState } from "react";
import { Form, DatePicker, Select, Space, Button, Modal } from "antd";
import ThePagination from "@/components/ThePagination";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import TheDialog from "@/components/TheDialog";
import TheImage from "@/components/TheImage";
import TheQueryForm from '@/components/TheQueryForm';
import TheTableExtend from '@/components/TheTableExtend'
import DynamicDetails from "@/views/users/component/DynamicDetails";
import { apiGetDynamicReportPage, apiGetDynamicReportRemove, apiGetDynamicComplaintDel, apiGetDynamicComplaintLabel } from '@/request/report'
import { getDateTime3 } from '@/utils/getDate'
import VideoPlayer from "@/components/VideoPlayer"
import _ from 'lodash'

const { RangePicker } = DatePicker;
let options = []
const SearchHeader = ({ setSearchValue }) => {
  const formRef = useRef()
  const [options, setOptions] = useState([])
  useEffect(async () => {
    let res = await apiGetDynamicComplaintLabel()
    if (res.code === 0) {
      let options = res.data.map(v => {
        return {
          value: v.complaintLabelId,
          label: v.complaintLabelName
        }
      })
      setOptions(options)
    }
  }, [])
  const reset = () => {
    formRef.current.setFieldsValue({
      time: [],
      complaintLabelId: null
    })
    setSearchValue({})
  };
  const onFinish = (value) => {
    if (value.time && value.time.length) {
      value.createStartTime = getDateTime3(value.time[0]) + ' 00:00:00'
      value.createEndTime = getDateTime3(value.time[1]) + ' 23:59:59'
    }
    delete (value.time)
    _.forIn(value, (v, k) => {
      if (!v) {
        delete (value[k])
      }
    })
    setSearchValue(value)
  }
  return (
    <div>
      <Form ref={formRef} onFinish={onFinish} layout="inline">
        <Form.Item name={"time"} label="举报时间">
          <RangePicker />
        </Form.Item>
        <Form.Item name={"complaintLabelId"} label="举报原因">
          <Select style={{ width: 200 }} options={options} placeholder="请选择举报原因" />
        </Form.Item>
        <Form.Item>
          <Space size="small" style={{ marginLeft: 10 }}>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button onClick={reset}>重置</Button>
          </Space>
        </Form.Item>
      </Form>
    </div>
  );
};

class DynamicReport extends React.Component {
  state = {
    columns: [
      {
        title: "举报用户",
        dataIndex: "nickName",
        key: "nickName",
      },
      {
        title: "举报时间",
        dataIndex: "createTime",
        key: "createTime",
      },
      {
        title: "被举报动态正文",
        dataIndex: "dynamicText",
        key: "dynamicText",
        render: (text, record) => {
          return <div style={{ width: 200, overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>{record.dynamicText}</div>
        }
      },
      {
        title: "被举报动态图片",
        dataIndex: "dynamicImages",
        key: "dynamicImages",
        render: (text, record) => {
          if(record.type === "video"){
            let arr = record.dynamicImages.split('|')
            return <TheImage preview={false} src={arr[1]} width={80} height={80} onClick={()=>{this.videoDialog(arr[0])}} />
          }else{
            let str = record.dynamicImages || ''
            return str.split(',').map(v => {
              return <TheImage src={v} width={80} height={80} />
            })
          }
        }
      },
      {
        title: "举报原因",
        dataIndex: "complaintLabelName",
        key: "complaintLabelName",
      },
      {
        title: "操作",
        fixed: 'right',
        render: (text, render) => {
          return (
            <div>
              <TheButton haspermi={['report:dynamic:detail']} onClick={() => this.setState({ visible: true, dynamicId: render.dynamicId })}>
                动态详情
              </TheButton>
              <TheButton haspermi={['report:dynamic:delete']} onClick={() => this.deleteConfirm(render.dynamicComplaintId, render.dynamicId)}>删除</TheButton>
              <TheButton haspermi={['report:dynamic:remove']} onClick={() => this.removeConfirm(render.dynamicComplaintId)}>移出</TheButton>
            </div >
          );
        },
      },
    ],
    dataSource: [],
    pageData: {
      pageNo: 1,
      pageSize: 10,
    },
    total: 0,
    visible: false,
    searchValue: {},
    dynamicId: "",
    options: '',
    searchOption: [
      { field: 'nickName', label: '举报用户', placeholder: '请输入举报用户', required: false, rules: [], type: 'Input', defaultValue: '' },
      { field: 'complaintLabelId', label: '举报原因', placeholder: '请选择举报原因', required: false, rules: [], type: 'Select', options: options,  defaultValue: ''},
      { field: 'time', label: '举报时间', required: false, rules: [], type: 'RangePicker' },
    ],
    newColumns: [],
    form_show: true,
    isvideoModalVisible:false,
    videoAddress:""
  };
  async componentDidMount() {
    this.onColumnsFilter(this.state.columns)
    this.complaintLabel()
    await this.getData()
  }
  // 举报原因下拉框数据
  async complaintLabel() {
    let res = await apiGetDynamicComplaintLabel()
    if (res.code === 0 && res.data) {
      options = res.data.map(v => {
        return {
          value: v.complaintLabelId,
          label: v.complaintLabelName
        }
      })
    }
  }
  
  getData = async (value) => {
    if(value && !_.isEmpty(value.time)){
      value.createStartTime = getDateTime3(value.time[0]) + ' 00:00:00'
      value.createEndTime = getDateTime3(value.time[1]) + ' 23:59:59'
      delete(value.time)
    }
    this.setState({
      searchValue: value === undefined ? this.state.searchValue : { ...value }
    },async() => {
      const { pageData, searchValue } = this.state
      let res = await apiGetDynamicReportPage({ ...pageData, ...searchValue })
      if (res.code === 0 && res.data) {
        this.setState({
          pageData: {
            pageNo: res.pageNo,
            pageSize: res.pageSize
          },
          total: res.totalCount,
          dataSource: res.data
        })
      }
    })
  }
  closeDialog = () => {
    this.setState({ visible: false });
  };
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: { pageNo, pageSize }
    }, () => this.getData())
  };
  videoDialog = (e) => {
    this.setState({
      isvideoModalVisible:true,
      videoAddress:e
    })
  }
  videoOk = async ()=>{
    this.setState({
        isvideoModalVisible:false,
        videoAddress:""
    })
  }
  deleteConfirm = (dynamicComplaintId, dynamicId) => {
    React.$confirm({
      title: "您确定删除此条动态吗？",
      onOk: async () => {
        let res = await apiGetDynamicComplaintDel({ dynamicComplaintId, dynamicId })
        if (res.code === 0) {
          React.$message({
            type: 'info',
            content: '删除成功'
          })
          this.getData()
        }
      },
    });
  };
  removeConfirm = (dynamicComplaintId) => {
    React.$confirm({
      title: "您确定从举报列表中移出此条被举报记录吗？",
      onOk: async () => {
        let res = await apiGetDynamicReportRemove({ dynamicComplaintId })
        if (res.code === 0) {
          React.$message({
            type: 'info',
            content: '移出成功'
          })
          this.getData()
        }
      },
    });
  };
  // setSearchValue = value => {
  //   this.setState({
  //     searchValue: value,
  //     pageData: {
  //       pageNo: 1,
  //       pageSize: 10
  //     }
  //   }, () => this.getData())
  // }
  // 搜索重置
  onReset = (value) => {
    this.setState({ 
      searchValue: value, 
      pageData: { 
        pageNo: 1, 
        pageSize: 10 
      } 
    }, () => this.getData())
  }
  // 刷新
  onTableRefresh() {
    this.getData()
  }
  // table表格
  onColumnsFilter(value) {
    this.setState({
      newColumns: value
    })
  }
  render() {
    const {
      visible,
      columns,
      dataSource,
      pageData: { pageNo, pageSize },
      total,
      dynamicId,
      searchOption,
      form_show,
      newColumns,
      isvideoModalVisible,videoAddress
    } = this.state;
    return (
      <div className="p-layout-box">
        {/* <SearchHeader setSearchValue={this.setSearchValue} /> */}
        <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
        onReset= {()=> this.onReset()} onGetValues={(values) => this.getData(values)} >
        </TheQueryForm>
        <TheTableExtend
          columns={columns}
          onFormTrigger={() => this.setState({ form_show: !this.state.form_show })}
          onTableRefresh={() => this.onTableRefresh()}
          onColumnsFilter={(value) => this.onColumnsFilter(value)}
        />
        <div className="p-layout-content-pagination">
          <TheTable scroll={{ x: 'max-content', y: '63vh' }} columns={newColumns} dataSource={dataSource} />
          <ThePagination
            pageNo={pageNo}
            pageSize={pageSize}
            total={total}
            pageChange={this.pageChange}
          />
        </div>
        <TheDialog
          title="动态详情"
          visible={visible}
          width={600}
          footer={null}
          handleCancel={this.closeDialog}
        >
          <DynamicDetails dynamicId={dynamicId} closeDialog={this.closeDialog} />
        </TheDialog>
        {isvideoModalVisible?
          <Modal visible={isvideoModalVisible} onOk={this.videoOk} onCancel={this.videoOk}>
            <VideoPlayer  src={videoAddress} />
          </Modal>:null}
      </div>
    );
  }
}

export default DynamicReport;
